package top.deepdesigner.shiro;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.deepdesigner.pojo.DtsAdmin;
import top.deepdesigner.service.DtsAdminService;
import top.deepdesigner.service.DtsPermissionService;
import top.deepdesigner.service.DtsRoleService;
import top.deepdesigner.util.AdminResponseCode;
import top.deepdesigner.util.bcrypt.BCryptPasswordEncoder;

import java.util.Set;

/**
 * 管理授权范围
 *
 * @author duanruiqing
 */
@Slf4j
public class AdminAuthorizingRealm extends AuthorizingRealm {
  @Autowired
  private DtsAdminService dtsAdminService;

  @Autowired
  private DtsRoleService roleService;

  @Autowired
  private DtsPermissionService permissionService;

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    //1、获取认证后的用户对象
    DtsAdmin dtsAdmin = (DtsAdmin) principals.getPrimaryPrincipal();

    //2、获取角色id
    Integer[] roleIds = dtsAdmin.getRoleIds();

    Set<String> roles = roleService.getRoleIdByIds(roleIds);
    System.out.println("roles = " + roles);
    Set<String> permissions = permissionService.getPermissionsByRoleId(roleIds);
    System.out.println("permissions = " + permissions);

    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

    authorizationInfo.setRoles(roles);

    authorizationInfo.setStringPermissions(permissions);

    //3、返回授权对象
    return authorizationInfo;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    //1、接收并转换token
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    //2、获取用户名和密码
    String username = upToken.getUsername();
    String password = new String(upToken.getPassword());

    //3、根据用户名查询管理员用户
    DtsAdmin dtsAdmin = dtsAdminService.findDtsAdminByUsername(username);
    //4、判断
    if (null == dtsAdmin) {
      log.error("【用户模块】用户名不正确 {}", AdminResponseCode.ADMIN_INVALID_ACCOUNT);
      throw new UnknownAccountException();
    }
    //校验密码
    if (!new BCryptPasswordEncoder().matches(password, dtsAdmin.getPassword())) {
      log.error("【用户模块】密码不正确 {}", AdminResponseCode.ADMIN_INVALID_PASSWORD);
      throw new IncorrectCredentialsException();
    }
    //是否被锁定
    Boolean deleted = dtsAdmin.getDeleted();
    if (deleted) {
      log.error("【用户模块】用户被锁定 {}", AdminResponseCode.ADMIN_LOCK_ACCOUNT);
      throw new LockedAccountException();
    }
    //5、返回值
    return new SimpleAuthenticationInfo(dtsAdmin, password, this.getName());
  }
}
